package cn.qdhlm.collectservice.core.handler;


import cn.qdhlm.collectservice.common.util.CodeUtil;
import cn.qdhlm.collectservice.common.util.ComUtil;
import cn.qdhlm.collectservice.core.component.Analyser;
import cn.qdhlm.collectservice.core.component.Checker;
import cn.qdhlm.collectservice.model.rocketmq.DeviceData;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.buffer.Unpooled;

import lombok.extern.log4j.Log4j2;
import org.apache.rocketmq.common.message.MessageExt;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Name: EmqxDataHandler
 * @Description: EmqxDataHandler
 * @Author: jiangcs
 */
@Log4j2
@Component
public class DataHandler {
    @Autowired
    private Analyser analyser;

    /**
     * DeviceData 的操作
     * @param msg
     */
    public void process(MessageExt msg) {
        // DeviceData
        String hexStr = ByteBufUtil.hexDump(Unpooled.wrappedBuffer(msg.getBody()));
        // 试图存起来
        DeviceData deviceData = new DeviceData();
        // 唯一标识
        deviceData.setId(msg.getMsgId());
        // 本来的主题
        deviceData.setTopic(msg.getProperty("KEYS"));
        // 从哪里来
        deviceData.setTag(msg.getTags());
        // 数据
        deviceData.setData(CodeUtil.hexStringToBase64String(hexStr));
        // 状态
        deviceData.setStatus(0);
        // 创建时间
        deviceData.setCreateTime(new Date());
        // DeviceData 空
        if (ComUtil.isEmpty(deviceData)) {
            log.error("process end: rocketId[{}] deviceData is null", deviceData.getId());
            return;
        }
        if (ComUtil.isEmpty(deviceData.getData())) {
            log.error("process end: rocketId[{}] deviceData.data is empty", deviceData.getId());
            return;
        }

        try {
            processData(deviceData);
        } catch (Exception e) {
            log.error("process exception:", e);
        }

        log.info("process end: rocketId[{}]", deviceData.getId());

    }

    /**
     * 处理 数据包
     *
     * @param deviceData
     */
    public void processData(DeviceData deviceData) throws Exception {
        // 数据报文
        ByteBuf byteBuf = Unpooled.wrappedBuffer(CodeUtil.base64StringToByteArray(deviceData.getData()));

        // rocket
        String rocketId = deviceData.getId();

        // 更新checkTime
        deviceData.setCheckTime(new Date());

        // 校验
        boolean checkFlag = Checker.check(byteBuf);
        if (checkFlag) {
            // 数据记录状态为 1：校验通过
            deviceData.setStatus(1);

            // 分析 报文
            Date dealTime = new Date();
            analyser.analysis(rocketId, byteBuf);

            // 更新 数据记录状态为 2：处理完成
            deviceData.setDealTime(dealTime);
            deviceData.setStatus(2);

        } else {
            // 数据记录状态为 -1：校验失败
            deviceData.setStatus(-1);

        }
    }
}
